import { readFileSync } from 'node:fs'

import type { HttpContext } from '@adonisjs/core/http'
import app from '@adonisjs/core/services/app'
import stringHelpers from '@adonisjs/core/helpers/string'
import { generateExcelResponse } from '#utils/xlsx'
import redis from '@adonisjs/redis/services/main'
import { GoodsFactory } from '#database/factories/goods_factory'

export default class IndexController {
  async index(ctx: HttpContext) {
    // redis.setex('token', 60, '123')
    // await GoodsFactory.createMany(10)

    const homeHtmlPath = app.makePath('./resources/home.html')
    const homeHtml = readFileSync(homeHtmlPath, 'utf-8')
    ctx.response.type('.html')
    return stringHelpers.interpolate(homeHtml, { version: app.version })
  }

  export({ response }: HttpContext) {
    try {
      const data = [
        ['商品', '数量', '单价'],
        ['测试1', 2, 3],
        ['测试1', false, null, 'sheetjs'],
        ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
        ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
        ['baz', null, 'qux'],
      ]
      generateExcelResponse(response, '测试2', data, {
        '!autofilter': {
          ref: 'A1:C3', // 这里可能需要根据您的需求修改
        },
        '!cols': [{ width: 30 }, { width: 30 }, { width: 30 }],
      })
    } catch (error) {
      console.error('导出表格时出错:', error)
      response.status(500).send('导出表格时出错')
    }
  }
}
